package com.qyl.honghengshop.dao.impl;

import java.util.List;
import java.util.Map;

import org.apache.ibatis.session.SqlSession;

import com.qyl.honghengshop.dao.BaseDao;
import com.qyl.honghengshop.dao.OrderDao;
import com.qyl.honghengshop.dto.Goods;
import com.qyl.honghengshop.dto.Order;
import com.qyl.honghengshop.dto.OrderItem;
import com.qyl.honghengshop.mapper.OrderItemMapper;
import com.qyl.honghengshop.mapper.OrderMapper;
import com.qyl.honghengshop.utils.PageBean;

public class OrderDaoImpl extends BaseDao implements OrderDao {

	@Override
	public int getRecordCount(Order order) {

		SqlSession sqlSession = this.getSqlSession();
		
		OrderMapper orderMapper = sqlSession.getMapper(OrderMapper.class);
		
		int recordCount = orderMapper.getRecordCount(order);
		
		this.closeSqlSession();
		
		return recordCount;
	}

	@Override
	public void orderList(PageBean pageBean, Order order) {

		SqlSession sqlSession = this.getSqlSession();
		
		OrderMapper orderMapper = sqlSession.getMapper(OrderMapper.class);
		
		List<Order> list = orderMapper.orderList(pageBean,order);
		
		pageBean.setList(list);
		
		this.closeSqlSession();
	}

	@Override
	public void saveOrder(Order order,Integer[] ids,Map<Integer, Integer> buyCard) {

		SqlSession sqlSession = this.getSqlSession();
		
		OrderMapper orderMapper = sqlSession.getMapper(OrderMapper.class);
		
		OrderItemMapper orderItemMapper = sqlSession.getMapper(OrderItemMapper.class);
		
		try {
			orderMapper.saveOrder(order);

			for (Integer goodId : ids) {
				//创建OrderItem对象,并补全对象数据
				OrderItem orderItem = new OrderItem();
			/*	System.out.println(1/0);*/
				Integer buyNum = buyCard.get(goodId);
				Order itemOrder = new Order();
				itemOrder.setId(order.getId());
				Goods itemGoods = new Goods();
				itemGoods.setId(goodId);
				orderItem.setOrder(itemOrder);
				orderItem.setGoods(itemGoods);
				orderItem.setOrder_num(buyNum);		
				orderItemMapper.saveOrderItem(orderItem);
			}
			
			sqlSession.commit();
			
		} catch (Exception e) {
			
			sqlSession.rollback();
			e.printStackTrace();
		}

		this.closeSqlSession();
		
	}

}
